<template>
  <div>
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 头部的警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="{ expandTrigger: 'hover', ...cascaderProps}"
            @change="cateListChanged"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="mini"
            type="primary"
            :disabled="selectedKeys.length!==3"
            @click="showAddDialog"
          >添加参数</el-button>
          <!-- 动态参数的table -->
          <el-table :data="manyParamList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag  @close="handleTagClose(scope.row, i)" closable v-for="(v,i) in scope.row.attr_vals" :key="i">{{v}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#">
              <template slot-scope="scope">{{scope.$index+1}}</template>
            </el-table-column>

            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEdit(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParam(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="mini"
            type="primary"
            :disabled="selectedKeys.length!==3"
            @click="showAddDialog"
          >添加属性</el-button>
          <!-- 静态属性table -->
          <el-table :data="onlyParamList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag  @close="handleTagClose(scope.row, i)" closable v-for="(v,i) in scope.row.attr_vals" :key="i">{{v}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 展开行结束 -->
            <el-table-column label="#">
              <template slot-scope="scope">{{scope.$index+1}}</template>
            </el-table-column>

            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEdit(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParam(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 点击按钮弹出的对话框 -->
    <el-dialog
      :title="titleTitleText"
      :visible.sync="showAddParamDialog"
      width="50%"
      @close="handleClose"
    >
      <el-form :model="paramForm" ref="paramFormRef" label-width="100px" :rules="paramFormRules">
        <el-form-item :label="titleText" required prop="attr_name">
          <el-input v-model="paramForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddParamDialog = false">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="activeName==='many'?'修改动态参数':'修改静态属性'"
      :visible.sync="showEditDialog"
      width="50%"
      @close="handleEditClose"
    >
      <el-form
        :model="paramForm"
        ref="paramEditFormRef"
        label-width="100px"
        :rules="paramFormRules"
      >
        <el-form-item :label="titleText" required prop="attr_name">
          <el-input v-model="paramForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="editConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      selectedKeys: [],
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      activeName: "many",
      // 参数属性列表
      attrList: [],
      // 动态参数列表
      manyParamList: [],
      // 静态参数列表
      onlyParamList: [],
      // 展示对话框
      showAddParamDialog: false,
      paramForm: {
        attr_name: ""
      },
      paramFormRules: {
        attr_name: [
          {
            required: true,
            message: "属性或参数不能为空！",
            trigger: "blur"
          }
        ]
      },
      showEditDialog: false
    };
  },
  computed: {
    // 当前选中的三级分类
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2];
      }
      return null;
    },
    // 对话框的标题
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
    titleTitleText() {
      if (this.activeName === "many") {
        return "添加动态参数";
      } else {
        return "添加静态属性";
      }
    }
  },
  methods: {
    // 关闭tag标签触发的事件
    async handleTagClose(row, i){
      row.attr_vals.splice(i, 1)
      // 修改该动态参数的参数列表
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status!==200) return this.$message.error('删除失败')
      this.$message.success('删除成功！')
    },
    // 处理新增标签就是参数属性回车和blur方法
    async handleInputConfirm(row) {
      if(row.inputValue.trim().length===0){
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      // 发起请求保存结果
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status!==200) return this.$message.error('添加失败')
      row.inputValue = ''
      row.inputVisible = false
      this.$message.success('添加成功')
    },
    // 点击新增标签
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 根据属性id删除属性
    async delParam(Id) {
      const resCf = await this.$msbox
        .confirm("确认删除该属性参数吗?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .catch(err => err);
      if (resCf === "cancel") return this.$message.info("已取消删除");
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${Id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.getParamsData();
      this.$message.success("删除成功");
    },
    editConfirm() {
      this.$refs.paramEditFormRef.validate(async valid => {
        if (!valid) return this.$message.error("表单验证未通过！");
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.paramForm.attr_id}`,
          {
            attr_name: this.paramForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.attr_vals
          }
        );
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("修改失败");

        this.$message.success("修改成功！");
        this.showEditDialog = false;
        this.getParamsData();
      });
    },
    // 修改对话框关闭触发实践
    handleEditClose() {
      this.$refs.paramEditFormRef.resetFields();
    },
    // 展示修改对话框
    async showEdit(Id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${Id}`
      );
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取属性参数失败");
      this.paramForm = res.data;
      this.showEditDialog = true;
    },
    // 确定添加属性或参数
    addConfirm() {
      this.$refs.paramFormRef.validate(async valid => {
        if (!valid) return this.$message.error("表单验证未通过！");
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.paramForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error("添加失败");

        this.$message.success("添加成功！");
        this.showAddParamDialog = false;
        this.getParamsData();
      });
    },
    // 关闭对话框
    handleClose() {
      this.$refs.paramFormRef.resetFields();
    },
    // 点击添加参数后
    showAddDialog() {
      this.showAddParamDialog = true;
    },
    // 监听tab 页签点击事件
    handleTabClick() {
      this.getParamsData();
    },
    // 获取所有的商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) this.$message.error("获取商品列表失败");
      this.cateList = res.data;
      // console.log(this.cateList);
    },
    // 当下拉框改变的时候
    cateListChanged() {
      this.getParamsData();
    },
    // 获取列表的参数数据
    async getParamsData() {
      if (this.cateId == null) {
        this.selectedKeys = []
        this.manyParamList = []
        this.onlyParamList = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("获取属性参数失败");
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyParamList = res.data;
        // console.log(this.manyParamList)
      } else {
        this.onlyParamList = res.data;
        // console.log(this.onlyParamList)
      }
    }
  },
  created() {
    this.getCateList();
  }
};
</script>

<style lang='less' scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 130px;
}
</style>
